package com.company;

public class ListNode<T> {
    private T data;
    private ListNode<?> next;

    public ListNode(T data) {
        this.data=data;
    }

/**
 * 链表的基本操作：一、遍历链表或统计长度
 */
public void traverse(ListNode<?> headNode){
    ListNode<?> currentNode=headNode;
        while (currentNode!=null){
            System.out.println(currentNode.data);
            currentNode=currentNode.next;
        }
    }
    /**
     * 二、单链表的长度
     */
    public int ListLength(ListNode<?> headNode){
        int length =0;
        ListNode<?> currentNode=headNode;
        while (currentNode!=null){
            length++;
            currentNode=currentNode.next;
        }
        return length;
    }

    /**
     * 单链表的插入
     * @param headNode
     * @param nodeToInsert
     * @param postition
     * @return
     */
    public ListNode<?> InsertInLink(ListNode<?> headNode,ListNode<?> nodeToInsert,int postition){
        if (headNode==null)return nodeToInsert;
        int size=ListLength(headNode);
        if (postition<1||postition>size+1){
            System.out.println("Position of to insert is invalid");
            return headNode;
        }
        if (postition==1){
                nodeToInsert.next=headNode;
                return nodeToInsert;
        }else{
            ListNode<?> previousNode=headNode;
            int count=1;
            while (count<size){
                previousNode=previousNode.next;
                count++;
            }
            nodeToInsert.next= previousNode.next;
            previousNode.next=nodeToInsert;
        }
        return headNode;
    }
    public ListNode<?> DeleteNode(ListNode<?> headNode,int position){
        int size=ListLength(headNode);
        if (position>size||position<1){
            System.out.println("Position of Node to delete is invalid.");
            return headNode;
        }
        if (position==1){
            ListNode<?> currentNode=headNode.next;
            headNode=null;
            return currentNode;
        }else{
            ListNode<?> previousNode =headNode;
            int count=1;
            while (count<position){
                previousNode=previousNode.next;
                count++;
            }
            ListNode<?> currentNode=previousNode.next;
            previousNode.next=currentNode.next;
            currentNode=null;
        }
        return headNode;
    }
    public void DeleteLinkedList(ListNode<?> headNode){
        ListNode<?> auxilaryNode,iterator=headNode;
        while (iterator!=null){
            auxilaryNode=iterator.next;
            iterator=null;
            iterator=auxilaryNode;
        }
    }
}
